import React, { useEffect } from 'react'; // 导入React和useEffect
import { Form, Input, Button, Card, message } from 'antd'; // 导入Ant Design组件
import { UserOutlined, LockOutlined } from '@ant-design/icons'; // 导入图标
import { useNavigate } from 'react-router-dom'; // 导入路由跳转

const Login = () => {
  const navigate = useNavigate(); // 获取跳转方法

  // 自动注册初始用户（仅首次加载时）
  useEffect(() => {
    // 检查本地是否已初始化过
    if (localStorage.getItem('initUser')) return;
    // 检查后端是否已有用户（简单用admin账号）
    fetch('http://localhost:3001/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: 'admin', password: 'admin123' })
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          // 已有admin用户
          localStorage.setItem('initUser', '1');
        } else {
          // 无admin用户，自动注册初始管理员和员工
          Promise.all([
            fetch('http://localhost:3001/api/users', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ username: 'admin', password: 'admin123', role: 'admin', realName: '系统管理员' })
            }),
            fetch('http://localhost:3001/api/users', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ username: 'staff', password: 'staff123', role: 'employee', realName: '普通员工' })
            })
          ]).then(() => {
            localStorage.setItem('initUser', '1');
            message.success('已自动初始化管理员和员工账号');
          });
        }
      });
  }, []);

  // 登录提交
  const onFinish = (values) => {
    // 调用后端登录接口
    fetch('http://localhost:3001/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: values.username, password: values.password })
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          // 保存用户信息到localStorage
          localStorage.setItem('user', JSON.stringify(data.user));
          message.success('登录成功');
          navigate('/');
        } else {
          message.error(data.error || '登录失败');
        }
      })
      .catch(() => message.error('网络错误'));
  };

  // 注册功能（可选，按钮注册新用户）
  const onRegister = (values) => {
    fetch('http://localhost:3001/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username: values.username,
        password: values.password,
        role: 'employee', // 默认注册为员工
        realName: values.username
      })
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          message.success('注册成功，请登录');
        } else {
          message.error(data.error || '注册失败');
        }
      })
      .catch(() => message.error('网络错误'));
  };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f0f2f5' }}>
      <Card title="电商后台管理系统登录" style={{ width: 350 }}>
        <Form onFinish={onFinish}>
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}> 
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}> 
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>登录</Button>
          </Form.Item>
        </Form>
        <Form onFinish={onRegister} style={{ marginTop: 16 }}>
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}> 
            <Input prefix={<UserOutlined />} placeholder="注册用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}> 
            <Input.Password prefix={<LockOutlined />} placeholder="注册密码" />
          </Form.Item>
          <Form.Item>
            <Button type="dashed" htmlType="submit" block>注册新员工</Button>
          </Form.Item>
        </Form>
        <div style={{ marginTop: 8, color: '#888', fontSize: 12 }}>
          默认管理员：admin / admin123<br />
          默认员工：staff / staff123
        </div>
      </Card>
    </div>
  );
};

export default Login; // 导出登录页面 